// 登录界面
let data = require('../controller/data')
let jwt = require("jsonwebtoken")
var appToken = require('../token_vertify.js');



function dateFormat(format) {
    var date = new Date();
    var format_arr = {
        "Y": date.getFullYear(),
        "m": date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : "0" + (date.getMonth() + 1),
        "d": date.getDate(),
        "H": date.getHours(),
        "i": date.getMinutes(),
        "s": date.getSeconds(),
    };
    for (var key in format_arr) {
        format = format.replace(key, format_arr[key]);
    }
    return format;
};


module.exports = {
    login:async function(req,res){
        let username = req.body.username
        let password = req.body.password
        let verify = req.body.verify

        // 判断接受数据是否存在
        if(!username){
            res.json({
                status:501,
                message:'请输入用户名'
            })
            return false;
        }
        if(!password){
            res.json({
                status:502,
                message:'请输入密码'
            })
            return false;
        }
        if(!verify){
            res.json({
                status:503,
                message:'请输入验证码'
            })
            return false;
        }

        // 查询数据库
        let result = await data.islogin([username,password])
        if(result){

            // let token = jwt.sign({username},'jwt',{
            //     expiresIn:60*60
            // })

            //JWT 是数字签名，所以只需要 public key 和受信任的时间即可验证有效性,所有服务器重启后，仍然有效，不需要存储，所以如果用户退出登录，其实之前的token仍然有效
            //如果需要主动退出登录后失效，只能应用层加管理，比如存数据库，数据库没有的就无效，数据库存在的再通过
            appToken.setToken(username).then((data)=>{
                return res.json({status:200, token: data,info:'logresinfo' });
            })
        }else{
            res.json({
                status:504,
                message:'用户名或密码错误'
            })
        }
    },
    register:async function(req,res) {
        let username = req.body.username
        let password = req.body.password
        // let verify = req.body.verify


        let now = dateFormat('Y-m-d H:i:s');
        // console.log("time:" + now);


        let result = await data.register([username,password,now]);
        console.log("register result:"+result);
        if (result)
        {
            return res.json({status:200,des:"register success"});
        }else {
            return res.json({status:201,des:"register fail"});
        }
    },


    allUsers:async function(req,res) {

        let result = await data.allUsers(null);
        if (result)
        {
            let array = new Array();
            for (let i = 0; i < result.length;i++)
            {
                let json = result[i];
                array.push(json.userName);
            }

            return res.json({status:200,res:array});
        }else {
            return res.json({status:201,des:"register fail"});
        }
    },

    verifylogin:async function(req,res){

        let token = req.headers['authorization'];

        if(!token){
            console.log("未获取到token");

            return res.json({status:301,des:"unlogin"});
        }else{
            // console.log("token="+token);
            appToken.verToken(token).then((data)=> {

                //用户信息赋值到请求信息里面，具体业务根据用户信息来对应操作
                req.data = data;
                //验证成功后，判断是那个用户
                console.log("token验证 账号:"+data.name);
                return res.json({status:200,des:"token验证有效"});
            }).catch((error)=>{
                console.log("token验证异常"+error);
                // return next(error);
                return res.json({status:301,des:"token验证失败"});
            })
        }
    }
}
